<template>
    <div class="app-container h-100">
        <!-- 搜索区域 -->
        <div class="search-container">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item v-if="dataType == '图表'" label="监测项目">
                    <el-select v-model="searchForm.pollutentCode" @change="handlePollutentChange" clearable placeholder="请选择监测项目">
                        <el-option v-for="item in pollutantList" :key="item.pollutantcode" :label="item.pollutantname"
                            :value="item.pollutantcode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker value-format="yyyy-MM-dd" v-model="searchForm.dateTime" type="date" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="dataType" @input="tabRuttonChange()">
                        <el-radio-button label="列表"></el-radio-button>
                        <el-radio-button label="图表"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table v-if="dataType == '列表'" :data="tableData || []" style="width: 100%" stripe>
            <el-table-column prop="id" label="序号" width="60" align="center">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="industry" label="行业" width="120" align="center"></el-table-column>
            <el-table-column label="本期" align="center">

                <el-table-column prop="011Value" label="COD (kg)" align="center">

                </el-table-column>
                <el-table-column prop="101Value" label="总磷 (kg)" align="center">

                </el-table-column>
                <el-table-column prop="065Value" label="总氮 (kg)" align="center">

                </el-table-column>
                <el-table-column prop="060Value" label="氨氮 (kg)" align="center">

                </el-table-column>
                <el-table-column prop="amountValue" label="合计 (kg)" align="center">

                </el-table-column>
            </el-table-column>

        </el-table>
        <div v-else style="height: calc(100% - 100px);">
            <div id="chart" class="h-100" ref="chartRef"></div>
        </div>
    </div>
</template>
<script>
import { buspollutantList, polluteTypeAnalyse } from "./api.js"
import * as echarts from "echarts";
export default {
    data() {
        return {
            dataType: '列表',
            searchForm: {
                pollutentCode: '',
                dateTime: '',
            },
            pollutantList: [],
            tableData: [],
        }
    },
    // 组件销毁时清理图表资源
    beforeDestroy() {
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }
    },
    created() {
        this.searchForm.dateTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        this.query();
    },
    methods: {
        async query() {
            await this.getbuspollutantList();
            this.getTableList();
        },
        handlePollutentChange() {
            // 监测项目改变时，清空图表数据
            this.chartInstance = null;
            this.getTableList();
        },
        tabRuttonChange() {

            // 切换标签时重新加载数据
            this.getTableList();
        },
        getTableList() {
            polluteTypeAnalyse({
                dateTime: this.searchForm.dateTime,
            }).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data;
                    if (this.dataType == '图表') {
                        this.initChart();
                    }
                }
            })

        },
        initChart() {
            // 如果dataType为图表且监测项目未被选中，默认选中第一个项目
            if (this.dataType === '图表' && !this.searchForm.pollutentCode && this.pollutantList && this.pollutantList.length > 0) {
                this.searchForm.pollutentCode = this.pollutantList[0].pollutantcode;
            }

            // 获取图表容器并初始化图表
            const chartDom = document.getElementById('chart');
            if (!chartDom) return;

            // 销毁已存在的图表实例
            if (this.chartInstance) {
                this.chartInstance.dispose();
            }

            const myChart = echarts.init(chartDom);

            // 准备图表数据
            // 使用模拟数据来确保图表能够显示
            let mockData = [];
            this.tableData.forEach(item => {
                mockData.push({
                    name: item.industry,
                    value: item[this.searchForm.pollutentCode + 'Value']
                });
            })
            
            const xAxisData = mockData.map(item => item.name);
            const seriesData = mockData.map(item => item.value);

            // 获取当前选中的污染物名称
            let pollutantName = '';
            if (this.searchForm.pollutentCode && this.pollutantList && this.pollutantList.length > 0) {
                const selectedPollutant = this.pollutantList.find(item => item.pollutantcode === this.searchForm.pollutentCode);
                if (selectedPollutant) {
                    pollutantName = selectedPollutant.pollutantname;
                }
            }

            // 设置图表配置项
            const option = {
                title: {
                    text: `各区划${pollutantName}排放量统计`,
                    left: 'center',
                    textStyle: {
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },

                    formatter: function (params) {
                        const value = params[0] && params[0].value !== undefined ? params[0].value : 0;
                        return `${params[0].name}: ${value.toLocaleString()} kg`;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: xAxisData,
                    axisLabel: {
                        interval: 0,
                        rotate: 30,
                        fontSize: 10
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'kg',
                    axisLabel: {
                        formatter: function (value) {
                            if (value >= 10000) {
                                return (value / 10000).toFixed(1) + 'w';
                            }
                            return value;
                        }
                    }
                },
                series: [{
                    name: `${pollutantName}（本期）`,
                    type: 'bar',
                    data: seriesData,
                    itemStyle: {
                        color: '#409eff'
                    },
                    label: {
                        show: false,
                        position: 'top',
                        formatter: '{c}'
                    }
                }]
            };

            // 设置图表配置并渲染
            myChart.setOption(option);

            // 保存图表实例引用
            this.chartInstance = myChart;

            // 使用Vue的nextTick确保在DOM渲染完成后再处理
            this.$nextTick(() => {
                // 首次渲染后调整图表大小以适应容器
                myChart.resize();
            });
        },


        handleSearch() {
            // 搜索时重新加载表格数据
            this.getTableList();
        },

        async getbuspollutantList() {
            let res = await buspollutantList();
            if (res.code == 200) {
                this.pollutantList = res.rows;
            }
        },
    },
}
</script>
<style></style>